package com.stack.knowyoubase.util;

import com.stack.knowyoubase.constant.GlobalConst;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * 邮件工具类
 *
 * @author stack
 */
@Component
public class EmailUtil {

    @Resource
    private JavaMailSender mailSender;

    private final char[] chars = "1234567890administrativelyABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    private final Random random = new Random();

    /**
     * 生成随机验证码
     *
     * @return 验证码
     */
    public String createCaptcha() {
        //springBuilder 可扩容字符串，2倍，效率低，线程安全
        StringBuilder captCha = new StringBuilder();
        int captChaLength = 4;
        for (int i = 0; i < captChaLength; i++) {
            captCha.append(chars[random.nextInt(chars.length)]);
        }
        return captCha.toString();
    }

    /**
     * 邮件发送
     *
     * @param subject    邮件目的（用户注册，密码找回）
     * @param mailTarget 目标邮箱
     * @param captcha    验证码
     * @throws Exception 邮件发送异常处理
     */
    public void sendCaptchaEmail(String subject, String mailTarget, String captcha) throws Exception {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setFrom(GlobalConst.EMAIL_USERNAME);
        message.setTo(mailTarget);
        message.setSentDate(new Date());
        String emailBody = "这是一封来知你的验证码,为了安全，请勿泄露！！！验证码 5 分钟内有效。验证码为:";
        message.setText(emailBody + captcha);
        mailSender.send(message);
    }
}
